package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import com.sky.vo.EmployeeOV;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5DigestAsHex.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }


    @Override
    public PageResult pageList(EmployeePageQueryDTO epqDTO) {
        int page = Math.toIntExact(Objects.isNull(epqDTO.getPage()) ? 1 : epqDTO.getPage());
        int pageSize = Math.toIntExact(Objects.isNull(epqDTO.getPageSize()) ? 10 : epqDTO.getPageSize());
        PageHelper.startPage(page, pageSize);
        //条件查询
        List<Employee> list = employeeMapper.selectList(epqDTO);
        Page<Employee> employeePage = (Page<Employee>) list;
        return new PageResult(employeePage.getTotal(), employeePage.getResult());
    }

    @Override
    public void create(EmployeeDTO employeeDTO) {
        //账号校验
        String username = employeeDTO.getUsername();
        if (!StringUtils.hasText(username) || username.length() < 3 || username.length() > 20) {
            throw new BaseException(MessageConstant.USERNAME_MISMATCH);
        }
        if (employeeMapper.selectCountByUsername(username) > 0) {
            throw new BaseException(MessageConstant.USERNAME_IS_EXISTS);
        }
        //名字校验
        String name = employeeDTO.getName();
        if (Objects.isNull(name) || !name.matches("^[\\u4e00-\\u9fa5a-zA-Z]{1,12}$")) {
            throw new BaseException(MessageConstant.NAME_IS_ERROR);
        }
        //手机号校验
        if (Objects.isNull(employeeDTO.getPhone()) || !employeeDTO.getPhone().matches("^(13\\d|14[5-9]|15[0-35-9]|16[6]|17[013-8]|18\\d|19[89])\\d{8}$")) {
            throw new BaseException(MessageConstant.PHONE_NUMBER_IS_ERROR);
        }
        //身份证校验
        if (!employeeDTO.getIdNumber().matches("^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$")) {
            throw new BaseException(MessageConstant.ID_NUMBER_IS_ERROR);
        }
        Employee employee = new Employee();
        //相同属性复制
        BeanUtils.copyProperties(employeeDTO, employee);
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(password);
        employee.setStatus(1);
        employeeMapper.insert(employee);
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        employeeMapper.updateStatus(employee);
    }

    @Override
    public EmployeeOV findEmpById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        EmployeeOV employeeOV = new EmployeeOV();
        BeanUtils.copyProperties(employee,employeeOV);
        return employeeOV;
    }

    @Override
    public void updateById(EmployeeDTO employeeDTO) {
        //账号校验
        String username = employeeDTO.getUsername();
        if (!StringUtils.hasText(username) || username.length() < 3 || username.length() > 20) {
            throw new BaseException(MessageConstant.USERNAME_MISMATCH);
        }
        if (employeeMapper.selectCountByUsernameAndId(username,employeeDTO.getId()) > 0) {
            throw new BaseException(MessageConstant.USERNAME_IS_EXISTS);
        }
        //名字校验
        String name = employeeDTO.getName();
        if (Objects.isNull(name) || !name.matches("^[\\u4e00-\\u9fa5a-zA-Z]{1,12}$")) {
            throw new BaseException(MessageConstant.NAME_IS_ERROR);
        }
        //手机号校验
        if (Objects.isNull(employeeDTO.getPhone()) || !employeeDTO.getPhone().matches("^(13\\d|14[5-9]|15[0-35-9]|16[6]|17[013-8]|18\\d|19[89])\\d{8}$")) {
            throw new BaseException(MessageConstant.PHONE_NUMBER_IS_ERROR);
        }
        //身份证校验
        if (!employeeDTO.getIdNumber().matches("^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$")) {
            throw new BaseException(MessageConstant.ID_NUMBER_IS_ERROR);
        }
        Employee employee = new Employee();
        //相同属性复制
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setStatus(1);
        employee.setUpdateTime(LocalDateTime.now());
        //操作的员工id
        employee.setUpdateUser(BaseContext.getCurrentId());
        BaseContext.removeCurrentId();
        employeeMapper.update(employee);
    }

    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //新旧密码是否一样
        if (Objects.equals(passwordEditDTO.getOldPassword(),passwordEditDTO.getNewPassword())){
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        Long id = BaseContext.getCurrentId();
        //新旧密码是否一样
        //查询账号密码
        Employee employee = employeeMapper.selectById(id);
        String password = employee.getPassword();
        //密码加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        //旧密码是否正确
        if (!Objects.equals(password,md5DigestAsHex)){
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
        }
        String md5DigestAsHex1 = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        employeeMapper.updatePassword(id,md5DigestAsHex1);
    }


}
